"""
多进程读写同一个文件
"""

import multiprocessing
import time

# 文件名
file_name = 'multi_process_file.txt'

# 向文件中写入数据
def write_file():
    with open(file_name, 'w') as f:
        idx = 1
        while True:
            f.write(f"Line {idx}\n")
            f.flush()  # 确保数据写入文件
            idx += 1
            time.sleep(0.5) # 睡眠0.5秒，模拟写入延迟

# 读取文件
def read_file():
    with open(file_name, 'r') as f:
        while True:
            line = f.readline()
            if not line:
                continue
            print(f"Read: {line.strip()}")
            time.sleep(0.5) # 睡眠0.5秒，模拟读取延迟

# 主程序
if __name__ == '__main__':
    # 创建一个子进程用于写文件
    p1 = multiprocessing.Process(target=write_file)
    p1.start()

    # 创建一个子进程用于读文件
    p2 = multiprocessing.Process(target=read_file)
    p2.start()

    # 等待子进程结束
    p1.join()
    p2.join()